<?php

namespace app\admin\controller\coupon;

use app\admin\model\User;
use app\common\controller\Backend;
use app\common\controller\Wanlshop;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;


/**
 * 卡券管理
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\index\model\wanlshop\Coupon;
        $this->view->assign("typeList", $this->model->getSysTypeList());
        $this->view->assign("usertypeList", $this->model->getUsertypeList());
        $this->view->assign("rangetypeList", $this->model->getRangetypeList());
        $this->view->assign("pretypeList", $this->model->getPretypeList());
    }
	
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where(['shop_id'=>0]) //商铺为0 代表系统优惠劵
                ->order($sort, $order)
                ->count();
    
            $list = $this->model
                ->where($where)
                ->where(['shop_id'=>0]) //商铺为0 代表系统优惠劵
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
    
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
    
            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 回收站
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->count();
    
            $list = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
    
            $result = array("total" => $total, "rows" => $list);
    
            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
    public function add()
    {
    	//设置过滤方法
    	$this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['shop_id'] = 0;
                $result = false;
                Db::startTrans();
                try {

					$params['surplus'] = 9999;
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		$this->assignconfig("row", $row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
	
	
	/**
	 * 删除
	 */
	public function del($ids = "")
	{
	    if ($ids) {
	        $pk = $this->model->getPk();
	        $this->model->where('shop_id', '=', 0);
	        $list = $this->model->where($pk, 'in', $ids)->select();
	
	        $count = 0;
	        Db::startTrans();
	        try {
	            foreach ($list as $k => $v) {
	                $count += $v->delete();
	            }
	            Db::commit();
	        } catch (PDOException $e) {
	            Db::rollback();
	            $this->error($e->getMessage());
	        } catch (Exception $e) {
	            Db::rollback();
	            $this->error($e->getMessage());
	        }
	        if ($count) {
	            $this->success();
	        } else {
	            $this->error(__('No rows were deleted'));
	        }
	    }
	    $this->error(__('Parameter %s can not be empty', 'ids'));
	}
	
	
	
	/**
	 * 还原
	 */
	public function restore($ids = "")
	{
	    $pk = $this->model->getPk();
	    $this->model->where('shop_id', '=', '0');
	    if ($ids) {
	        $this->model->where($pk, 'in', $ids);
	    }
	    $count = 0;
	    Db::startTrans();
	    try {
	        $list = $this->model->onlyTrashed()->select();
	        foreach ($list as $index => $item) {
	            $count += $item->restore();
	        }
	        Db::commit();
	    } catch (PDOException $e) {
	        Db::rollback();
	        $this->error($e->getMessage());
	    } catch (Exception $e) {
	        Db::rollback();
	        $this->error($e->getMessage());
	    }
	    if ($count) {
	        $this->success();
	    }
	    $this->error(__('No rows were updated'));
	}



    /**
     * 发送优惠劵
     */
    public function send()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $coupon = model('app\api\model\wanlshop\Coupon')->get($params['coupon_type']);
            if(!$coupon){
                $this->error(__('网络繁忙或优惠券不存在'));
            }

            // 判断优惠券是否过期
            $endtime = 0;
            if($coupon['pretype'] == 'fixed'){
                $endtime = strtotime($coupon['enddate']) + 86399;
                if(time() > $endtime){
                    $this->error(__('此张优惠券已经过期了'));
                }
            }else{
                if($coupon['validity'] > 0){
                    $endtime =  strtotime($coupon['validity'].' day',time());
                }
            }
            $where = [];
            if($params['user_ids']) {
                $user_ids = explode(',',$params['user_ids']) ;
                $where['id'] =['in',$user_ids];
            }
            $userList = (new User())->field('id, nickname')->where($where)->select();
            if ($params && $userList) {
                $result = false;
                Db::startTrans();
                try {
                    $CouponReceiveModel = model('app\api\model\wanlshop\CouponReceive');
                    foreach ($userList as $v){
                        $datas[] =[
                            'state'=>1,
                            'coupon_id'=>$coupon['id'],
                            'coupon_no'=>Random::alnum(16),
                            'user_id'=>$v['id'],
                            'shop_id'=>$coupon['shop_id'],
                            'type'=>$coupon['type'],
                            'name'=>$coupon['name'],
                            'userlevel'=>$coupon['userlevel'],
                            'usertype'=>$coupon['usertype'],
                            'price'=>$coupon['price'],
                            'discount'=>$coupon['discount'],
                            'limit'=>$coupon['limit'],
                            'rangetype'=>$coupon['rangetype'],
                            'range'=>$coupon['range'],
                            'pretype'=>$coupon['pretype'],
                            'validity'=>$coupon['validity'],
                            'startdate'=>$coupon['startdate'],
                            'enddate'=>$coupon['enddate'],
                            'createtime'=>time(),
                            'endtime'=>$endtime
                        ];
                    }
                    $inserCount = $CouponReceiveModel->insertAll($datas);
                    $coupon->allowField(true)->save(['alreadygrant'=>$coupon['alreadygrant'] + $inserCount]);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("couponList", $this->model->field('id,name')->where('shop_id','0')->select());
        return $this->view->fetch();
    }


    /**
     * 用户列表
     */
    public function userList()
    {
        if ($this->request->isAjax()) {
            // 1.1.4升级
            $keyValue = $this->request->request('name');
            if ($keyValue){
                $where['nickname'] = ['like','%' . $keyValue . '%'];
            }
            $where['status'] = 'normal';
            $where['is_shop'] = 0;
            $total = (new User())->where($where)->count();
            $list = (new User())->field('id, nickname as name')->where($where)->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
    }
	
	
	
	
}
